import json
import re
import random
from django.db.models import Q
from user import models
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.jwttool import meansjwt
from utils.sendcode import sms
from utils.redis import redistool
from django.core.files.storage import default_storage
from django.core.cache import caches
from utils.middlewares import MyAuthorization
import uuid


# Create your views here.

class loginin(APIView):
    def post(self, request):
        usercode = request.data.get('usercode', "")
        password = request.data.get('password', "")
        if not usercode or not password:
            return Response({"msg": "账号密码不可以为空"})
        info = models.user.objects.filter(Q(usercode=usercode) | Q(phone=usercode) | Q(email=usercode),
                                          isdel=False).first()
        if not info:
            return Response({"msg": "账号不可用"})
        else:
            if info.password != password:
                return Response({"msg": "密码错误"})
            else:
                return Response({"msg": "登录成功", "code": 200, "data": {
                    "userid": info.id,
                    "token": meansjwt.gettoken({"userid": info.id})
                }})


class sendcode(APIView):
    def post(self, request):
        phone = request.data.get("phone", "")
        result = re.match(r"^1[3-9]\d{9}$", phone)
        if not result:
            return Response({"msg": "手机号格式不正确"})
        if redistool.get_code(phone):
            return Response({"msg": "验证码已发送请稍后重试"})
        code = random.randint(1000, 9999)
        if json.loads(sms.send(phone, code))['statusCode'] == '000000':
            redistool.set_code(phone, code)
            return Response({"msg": "发送成功", "code": 200})
        else:
            return Response({"msg": "发送失败请重试", "code": 400})


class indentifycode(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        if not phone or not code:
            return Response({'msg': '手机号或验证码不可为空', "code": 400})
        result = re.match(r"^1[3-9]\d{9}$", phone)
        if not result:
            return Response({"code": "400", "msg": "手机号格式不正确"})
        else:
            resultcode = redistool.get_code(phone)
            if resultcode != code:
                return Response({'msg': '验证码输入错误', "code": 400})
            else:
                info = models.user.objects.filter(phone=phone).first()
                if not info:
                    models.user.objects.create(phone=phone)
                    info = models.user.objects.filter(phone=phone).first()
                userid = info.id
                token = meansjwt.gettoken({'userid': userid})
                return Response({'msg': '登录成功', "code": 200, "token": token})


class userinfo(APIView):
    authentication_classes = [MyAuthorization]  # 主要要用列表的形式设置类

    def get(self, request):
        id = request.query_params.get('userid')
        if not id:
            return Response({'msg': '用户id不可以为空', "code": 400})
        else:
            info = models.user.objects.filter(id=id).first()
            if not info:
                return Response({'msg': '用户不存在', "code": 400})
            else:
                info = models.user.objects.filter(id=id).values()[0]
                return Response({"msg": "ok", "code": 200, "info": info})


class Register(APIView):
    def post(self, request):
        usercode = request.data.get('usercode', "")
        phone = request.data.get('phone', "")
        email = request.data.get('email', "")
        password = request.data.get('password', "")
        if not usercode and not phone and not email:
            return Response({"msg": "账号密码邮箱不可同时为空"})
        if usercode:
            info = models.user.objects.filter(usercode=usercode).first()
            if info:
                return Response({"msg": "账号已存在！"})
            if not password:
                return Response({"msg": "密码不可为空"})
        if phone:
            phoneresult = re.match(r"^1[3-9]\d{9}$", phone)
            if not phoneresult:
                return Response({"msg": "手机号格式错误"})
            info = models.user.objects.filter(phone=phone).first()
            if info:
                return Response({"msg": "手机号已存在！"})
        if email:
            emailresult = re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', email)
            if not emailresult:
                return Response({"msg": "邮箱格式错误"})
            info = models.user.objects.filter(email=email).first()
            if info:
                return Response({"msg": "邮箱已存在！"})
        if password:
            # 或者验证密码的正则
            if len(password) < 6:
                return Response({"msg": "密码不可以少于6位"})
        info = models.user.objects.create(
            usercode=usercode,
            phone=phone,
            email=email,
            password=password,
        )
        if info:
            return Response({"msg": "注册成功", "code": 200})
        else:
            return Response({"msg": "注册失败", "code": 400})


class uploadimg(APIView):
    def post(self, request):
        file = request.data.get('file')
        if not file:
            return Response({"msg": "图片不可为空", "code": 400})
        if file.size > 1024 * 1024 * 2:
            return Response({"msg": "图片不可超过2MB", "code": 400})
        alltype = ["png", "jpg", "jpeg", "gif"]
        name = file.name.split(".")[1]  # 取到后缀名
        if name not in alltype:
            return Response({"msg": "格式不支持", "code": 400})
        rename = uuid.uuid4().hex + "." + name
        fileobj = default_storage.save("user/" + rename, file)
        url = default_storage.url(fileobj)
        return Response({"msg": "ok", "url": url})


